package com.ck.common.controller;

import com.ck.chuangke.service.CkCompanyService;
import com.ck.common.service.UserService;
import com.ck.constant.BusinessConstant;
import com.ck.constant.RequestConstant;
import com.ck.constant.ResponseConstant;
import com.ck.exception.ControllerException;
import com.ck.exception.ServiceException;
import com.ck.model.common.User;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.common.vo.UserListVO;
import com.ck.util.HttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;

/**
 * 用户Controller
 *
 * @author dxy
 * @date 2018/6/21 15:13
 */
@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private CkCompanyService companyService;

	/**
	 * 跳转至修改密码界面
	 */
	@RequestMapping(value = "/goUpdatePassword")
	public String goUpdatePassword() {
		return "common/password_update";
	}

	/**
	 * 修改密码
	 */
	@ResponseBody
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public Object updatePassword(String originalPassword, String newPassword, String confirmPassword, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String ip = HttpUtils.getRemortIP(request);
		if (StringUtils.isBlank(originalPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "原始密码不能为空");
		}
		String originalPasswordMd5 = DigestUtils.md5Hex(originalPassword);
		if (!originalPasswordMd5.equals(loginUser.getPassword())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "原始密码不正确");
		}
		if (StringUtils.isBlank(newPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "新密码不能为空");
		}
		if (StringUtils.isBlank(confirmPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "确认密码不能为空");
		}
		if (!newPassword.equals(confirmPassword)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "新密码和确认密码不一致");
		}
		Long userId = loginUser.getUserId();
		User passwordUser = new User();
		passwordUser.setUserId(userId);
		passwordUser.setPassword(newPassword);
		try {
			userService.updatePassword(passwordUser, loginUser, ip);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController updatePassword 修改密码失败：" + e.getMessage());
			return new ControllerException("修改密码失败： " + e.getMessage());
		}
		//从session中删除登录用户信息
		request.getSession().removeAttribute(RequestConstant.SESSION_KEY_USER);
		return "";
	}

	/**
	 * 保存用戶
	 */
	@ResponseBody
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Object saveUser(User user, String roleIds, HttpServletRequest request) {
		String userName = user.getUserName();
		if (StringUtils.isBlank(userName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用戶名称不能为空");
		}
		String password = user.getPassword();
		if (StringUtils.isBlank(password)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码不能为空");
		}
		//验证用户名
		User oldUser = userService.getUserByUserName(userName);
		if (oldUser != null) {
			String oldUserName = oldUser.getUserName();
			if (oldUserName.equals(userName)) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "用戶名称已存在，请重新输入");
			}
		}
		try {
			userService.insertUser(user, roleIds, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController saveUser 保存用戶失败：" + e.getMessage());
			return new ControllerException("保存用戶失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 修改用户
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Object updateUser(User user, String roleIds, HttpServletRequest request) {
		// 参数验证
		String userName = user.getUserName();
		if (StringUtils.isBlank(userName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用戶名称不能为空");
		}
		User oldUser = userService.getUserByUserName(userName);
		if (oldUser != null) {
			// 判断是否为超级管理员
			Integer superAdminUser = oldUser.getSuperAdminUser();
			if (superAdminUser != null) {
				if(BusinessConstant.SUPER_ADMIN_USER_YES == superAdminUser) {
					return new JsonResponse(ResponseConstant.CODE_FAIL, "超级管理员不允许修改");
				}
			}
			//判断用户名是否存在
			String oldUserName = oldUser.getUserName();
			if (oldUserName.equals(userName)) {
				//如果用户名相同，但是用户ID不一样
				if (!oldUser.getUserId().equals(user.getUserId())) {
					return new JsonResponse(ResponseConstant.CODE_FAIL, "用戶名称已存在，请重新输入");
				}
			}
		}
		try {
			userService.updateUser(user, roleIds, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController updateUser 修改用户失败：" + e.getMessage());
			return new ControllerException("修改用户失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 用户列表
	 */
	@RequestMapping(value = "/list")
	public String listUser(Integer status, String userName, Integer pageNum, Integer pageSize, HttpServletRequest request, Model model) {
		try {
			User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			String companyCode = user.getCompanyCode();
			PageInfo<UserListVO> pageInfo = userService.listUser(companyCode, status, userName, pageNum, pageSize);
			model.addAttribute("companyCode", companyCode);
			model.addAttribute("status", status);
			model.addAttribute("userName", userName);
			model.addAttribute("userList", pageInfo.getList());
			model.addAttribute("pageNum", pageInfo.getPageNum());
			model.addAttribute("pageSize", pageInfo.getPageSize());
			model.addAttribute("total", pageInfo.getTotal());
		} catch (ServerException e) {
			e.printStackTrace();
			logger.error("UserController listUser 用户列表失败：" + e.getMessage());
		}
		return "common/user_list";
	}

	/**
	 * 启用禁用用户
	 */
	@ResponseBody
	@RequestMapping(value = "/enableDisableUser", method = RequestMethod.POST)
	public Object enableDisableUser(User user, HttpServletRequest request) {
		if (user.getUserId() == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户ID不能为空，请联系管理员");
		}
		User optUser = userService.getUserById(user.getUserId());
		if(null == optUser){
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户已被删除或不存在");
		}
		if(optUser.getSuperAdminUser() == BusinessConstant.SUPER_ADMIN_USER_YES){
			return new JsonResponse(ResponseConstant.CODE_FAIL, "超级管理员不允许禁用");
		}
		try {
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			String remortIP = HttpUtils.getRemortIP(request);
			userService.enableDisableUser(user, loginUser, remortIP);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("UserController enableDisableUser 启用禁用用户失败：" + e.getMessage());
			return new ControllerException("启用禁用用户失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 重置密码
	 */
	@ResponseBody
	@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
	public Object resetPassword(Long userId, String password, HttpServletRequest request) {
		if (userId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户ID不能为空，请联系管理员");
		}
		if (StringUtils.isBlank(password)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码不能为空，请联系管理员");
		}
		//当前登录用户
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		if (loginUser == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "当前登录用户信息为空，请联系管理员");
		}
		//远程ip
		String remortIP = HttpUtils.getRemortIP(request);
		try {
			userService.resetPassword(userId, password, loginUser, remortIP);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("UserController resetPassword 重置密码失败：" + e.getMessage());
			return new ControllerException("重置密码失败" );
		}
		return "";
	}

}
